package com.shisfish.library.Timing;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import com.shisfish.library.Impl.BookLoanImpl;
import com.shisfish.library.Impl.BookMessageImpl;
import com.shisfish.library.Impl.UserSingleLendImpl;
import com.shisfish.library.Model.BookLoan;
import com.shisfish.library.Model.BookMessage;
import com.shisfish.library.Model.UserSingleLend;

public class BookLoanMessage extends TimerTask {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
		// 找到未取消，被提醒过的
		List<BookLoan> bookLoans = new BookLoanImpl().selectByType(1);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -3);
		if (bookLoans.size() > 0) {
			for (BookLoan bookLoan : bookLoans) {
				// 若有超期的，取消该预约
				if (bookLoan.getRemindTime().before(cal.getTime())) {
					bookLoan.setActualCancelTime(new Date());
					new BookLoanImpl().updateOne(bookLoan);
					
					// 把该isbn下的bookMessage 的number -1
					List<BookMessage> bookMessages = new BookMessageImpl().selectByKey(bookLoan.getIsbn());
					if (bookMessages.size() > 0) {
						BookMessage bookMessage = bookMessages.get(0);
						int number = bookMessage.getNumber() - 1;
						bookMessage.setNumber(number > 0 ? number : 0);
					}
					
					// 把相应用户的预约书的记录取消
					UserSingleLend userSingleLend = new UserSingleLendImpl().selectByEmployee(bookLoan.getLoaner());
					if (userSingleLend != null) {
						userSingleLend.setLoaned_number(userSingleLend.getLoaned_number() - 1);
						new UserSingleLendImpl().updateOne(userSingleLend);
					}
					
				}
			}
		} else {
			System.out.println("预约没有超期的");
		}
		
		// 找到未取消，未提醒过的
		/*List<BookLoan> bookLoanss = new BookLoanImpl().selectByType(2);
		if (bookLoanss.size() > 0) {
			cal.add(Calendar.DAY_OF_YEAR, -3);
			for (BookLoan bookLoan : bookLoanss) {
				if (bookLoan.getShouldCancelTime().before(cal.getTime())) {
					bookLoan.setActualCancelTime(new Date());
					new BookLoanImpl().updateOne(bookLoan);
				}
			}
		} else {
			System.out.println("没啥事");
		}*/
	}

}
